import PureRunnableRuntime from '../components/runnable-runtime';
import * as RunnableGroupAction from 'actions/runnable-group';
import * as RunnableUnitAction from 'actions/runnable-unit';
import { getFetchStatus, invalidateCache } from 'actions/util';
import * as BuilderAction from 'actions/builder';
import * as ReactRedux from 'react-redux';
import _ from 'lodash';

const mapStateToProps = (state, ownProps) => {
  const unitIds = state.runnableUnitIdsByRuntimeId[ownProps.id] || [];
  const originUnits = _.values(_.pick(state.runnableUnitsById, unitIds));
  let units;
  if (_.isEmpty(originUnits)) {
    units = [];
  } else {
    const unitsGroupByParentId = _.groupBy(originUnits, unit => unit.parentId || 0);
    units = unitsGroupByParentId[0].map(parentUnit => {
      return {
        ...parentUnit,
        children: unitsGroupByParentId[parentUnit.id]
      };
    });
    units = _.sortBy(units, (unit) => {
      if (unit.type === 'LINNER') {
        return 1;
      }
      if (unit.type === 'DOCKER_IMAGE') {
        return 100;
      }
      return 10;
    });
  }
  return {
    isFetching: getFetchStatus(state, RunnableGroupAction.listUnitsByRuntimeId, ownProps.id),
    isBuilding: getFetchStatus(state, BuilderAction.newBuild),
    unitDeleteFetching: getFetchStatus(state, RunnableUnitAction.deleteUnit),
    units
  };
};

const mapDispatchToProps = (dispatch, ownProps) => {
  const { id: runtimeId, groupId } = ownProps;

  return {
    onRefresh: () => {
      invalidateCache(RunnableGroupAction.listUnitsByRuntimeId, runtimeId);
      invalidateCache(RunnableGroupAction.listGroupMachines);
      dispatch(RunnableGroupAction.listUnitsByRuntimeId(runtimeId));
      dispatch(RunnableGroupAction.listGroupMachines(groupId));
    },
    onUnitDelete: (unitId) => {
      return dispatch(RunnableUnitAction.deleteUnit(unitId))
        .then(({ error }) => {
          if (!error) {
            invalidateCache(RunnableGroupAction.listUnitsByRuntimeId, runtimeId);
            dispatch(RunnableGroupAction.listUnitsByRuntimeId(runtimeId));
          }
        });
    }
  };
};

export default ReactRedux.connect(mapStateToProps, mapDispatchToProps)(PureRunnableRuntime);
